package logger

import (
	"common_demo/internal/config"

	"go.uber.org/zap"
)

var l *ilog

type ilog struct {
	*zap.SugaredLogger
}

// 初始化Logger
func InitLogger(config *config.LoggerConfig, opts ...Option) error {
	var err error

	l = new(ilog)
	if l.SugaredLogger, err = NewLogger(config, opts...); err != nil {
		return err
	}
	return nil
}

// 生成一个Logger
func NewLogger(config *config.LoggerConfig, opts ...Option) (*zap.SugaredLogger, error) {
	var err error

	option := newOption()
	for _, opt := range opts {
		opt(option)
	}

	zapConf := zap.NewProductionConfig()
	zapConf.OutputPaths = append(zapConf.OutputPaths, config.OutputPaths...)
	zapConf.ErrorOutputPaths = append(zapConf.ErrorOutputPaths, config.ErrorOutputPaths...)
	zapConf.Level, err = zap.ParseAtomicLevel(config.Level)
	if err != nil {
		return nil, err
	}

	logger, err := zapConf.Build()
	if err != nil {
		return nil, err
	}
	core := newInterceptorCore(logger.Core(), option.interceptor)

	return zap.New(core, option.zapOptions...).Sugar(), nil
}

func Debugf(template string, args ...interface{}) {
	l.SugaredLogger.Debugf(template, args...)
}

func Infof(template string, args ...interface{}) {
	l.SugaredLogger.Infof(template, args...)
}

func Errorf(template string, args ...interface{}) {
	l.SugaredLogger.Errorf(template, args...)
}

func Warnf(template string, args ...interface{}) {
	l.SugaredLogger.Warnf(template, args...)
}

func Fatalf(template string, args ...interface{}) {
	l.SugaredLogger.Fatalf(template, args...)
}

func Panicf(template string, args ...interface{}) {
	l.SugaredLogger.Panicf(template, args...)
}

func Sync() error {
	return l.SugaredLogger.Sync()
}
